# Constants for caption generation, copied from the original JoyCaption GGUF node
CAPTION_TYPE_MAP = {
	"Descriptive": [
		"Write a detailed description for this image.",
		"Write a detailed description for this image in {word_count} words or less.",
		"Write a {length} detailed description for this image.",
	],
	"Descriptive (Casual)": [
		"Write a descriptive caption for this image in a casual tone.",
		"Write a descriptive caption for this image in a casual tone within {word_count} words.",
		"Write a {length} descriptive caption for this image in a casual tone.",
	],
	"Straightforward": [
		"Write a straightforward caption for this image. Begin with the main subject and medium. Mention pivotal elements—people, objects, scenery—using confident, definite language. Focus on concrete details like color, shape, texture, and spatial relationships. Show how elements interact. Omit mood and speculative wording. If text is present, quote it exactly. Note any watermarks, signatures, or compression artifacts. Never mention what's absent, resolution, or unobservable details. Vary your sentence structure and keep the description concise, without starting with “This image is…” or similar phrasing.",
		"Write a straightforward caption for this image within {word_count} words. Begin with the main subject and medium. Mention pivotal elements—people, objects, scenery—using confident, definite language. Focus on concrete details like color, shape, texture, and spatial relationships. Show how elements interact. Omit mood and speculative wording. If text is present, quote it exactly. Note any watermarks, signatures, or compression artifacts. Never mention what's absent, resolution, or unobservable details. Vary your sentence structure and keep the description concise, without starting with “This image is…” or similar phrasing.",
		"Write a {length} straightforward caption for this image. Begin with the main subject and medium. Mention pivotal elements—people, objects, scenery—using confident, definite language. Focus on concrete details like color, shape, texture, and spatial relationships. Show how elements interact. Omit mood and speculative wording. If text is present, quote it exactly. Note any watermarks, signatures, or compression artifacts. Never mention what's absent, resolution, or unobservable details. Vary your sentence structure and keep the description concise, without starting with “This image is…” or similar phrasing.",
	],
	"Stable Diffusion Prompt": [
		"Output a stable diffusion prompt that is indistinguishable from a real stable diffusion prompt.",
		"Output a stable diffusion prompt that is indistinguishable from a real stable diffusion prompt. {word_count} words or less.",
		"Output a {length} stable diffusion prompt that is indistinguishable from a real stable diffusion prompt.",
	],
	"MidJourney": [
		"Write a MidJourney prompt for this image.",
		"Write a MidJourney prompt for this image within {word_count} words.",
		"Write a {length} MidJourney prompt for this image.",
	],
	"Danbooru tag list": [
		"Generate only comma-separated Danbooru tags (lowercase_underscores). Strict order: `artist:`, `copyright:`, `character:`, `meta:`, then general tags. Include counts (1girl), appearance, clothing, accessories, pose, expression, actions, background. Use precise Danbooru syntax. No extra text.",
		"Generate only comma-separated Danbooru tags (lowercase_underscores). Strict order: `artist:`, `copyright:`, `character:`, `meta:`, then general tags. Include counts (1girl), appearance, clothing, accessories, pose, expression, actions, background. Use precise Danbooru syntax. No extra text. {word_count} words or less.",
		"Generate only comma-separated Danbooru tags (lowercase_underscores). Strict order: `artist:`, `copyright:`, `character:`, `meta:`, then general tags. Include counts (1girl), appearance, clothing, accessories, pose, expression, actions, background. Use precise Danbooru syntax. No extra text. {length} length.",
	],
	"e621 tag list": [
		"Write a comma-separated list of e621 tags in alphabetical order for this image. Start with the artist, copyright, character, species, meta, and lore tags (if any), prefixed by 'artist:', 'copyright:', 'character:', 'species:', 'meta:', and 'lore:'. Then all the general tags.",
		"Write a comma-separated list of e621 tags in alphabetical order for this image. Start with the artist, copyright, character, species, meta, and lore tags (if any), prefixed by 'artist:', 'copyright:', 'character:', 'species:', 'meta:', and 'lore:'. Then all the general tags. Keep it under {word_count} words.",
		"Write a {length} comma-separated list of e621 tags in alphabetical order for this image. Start with the artist, copyright, character, species, meta, and lore tags (if any), prefixed by 'artist:', 'copyright:', 'character:', 'species:', 'meta:', and 'lore:'. Then all the general tags.",
	],
	"Rule34 tag list": [
		"Write a comma-separated list of rule34 tags in alphabetical order for this image. Start with the artist, copyright, character, and meta tags (if any), prefixed by 'artist:', 'copyright:', 'character:', and 'meta:'. Then all the general tags.",
		"Write a comma-separated list of rule34 tags in alphabetical order for this image. Start with the artist, copyright, character, and meta tags (if any), prefixed by 'artist:', 'copyright:', 'character:', and 'meta:'. Then all the general tags. Keep it under {word_count} words.",
		"Write a {length} comma-separated list of rule34 tags in alphabetical order for this image. Start with the artist, copyright, character, and meta tags (if any), prefixed by 'artist:', 'copyright:', 'character:', and 'meta:'. Then all the general tags.",
	],
	"Booru-like tag list": [
		"Write a list of Booru-like tags for this image.",
		"Write a list of Booru-like tags for this image within {word_count} words.",
		"Write a {length} list of Booru-like tags for this image.",
	],
	"Art Critic": [
		"Analyze this image like an art critic would with information about its composition, style, symbolism, the use of color, light, any artistic movement it might belong to, etc.",
		"Analyze this image like an art critic would with information about its composition, style, symbolism, the use of color, light, any artistic movement it might belong to, etc. Keep it within {word_count} words.",
		"Analyze this image like an art critic would with information about its composition, style, symbolism, the use of color, light, any artistic movement it might belong to, etc. Keep it {length}.",
	],
	"Product Listing": [
		"Write a caption for this image as though it were a product listing.",
		"Write a caption for this image as though it were a product listing. Keep it under {word_count} words.",
		"Write a {length} caption for this image as though it were a product listing.",
	],
	"Social Media Post": [
		"Write a caption for this image as if it were being used for a social media post.",
		"Write a caption for this image as if it were being used for a social media post. Limit the caption to {word_count} words.",
		"Write a {length} caption for this image as if it were being used for a social media post.",
	],
}

CAPTION_LENGTH_CHOICES = (["any", "very short", "short", "medium-length", "long", "very long"] + [str(i) for i in range(20, 261, 10)])

def build_prompt(caption_type: str, caption_length: str | int, extra_options: list[str], name_input: str) -> str:
	if caption_type not in CAPTION_TYPE_MAP:
		print(f"Warning: Unknown caption_type '{caption_type}'. Using default.")
		default_template_key = list(CAPTION_TYPE_MAP.keys())[0] 
		prompt_templates = CAPTION_TYPE_MAP.get(caption_type, CAPTION_TYPE_MAP[default_template_key])
	else:
		prompt_templates = CAPTION_TYPE_MAP[caption_type]

	if caption_length == "any": map_idx = 0
	elif isinstance(caption_length, str) and caption_length.isdigit(): map_idx = 1
	else: map_idx = 2
	
	if map_idx >= len(prompt_templates): map_idx = 0 

	prompt = prompt_templates[map_idx]
	if extra_options: prompt += " " + " ".join(extra_options)
	
	try:
		return prompt.format(name=name_input or "{NAME}", length=caption_length, word_count=caption_length)
	except KeyError as e:
		print(f"Warning: Prompt template formatting error for caption_type '{caption_type}', map_idx {map_idx}. Missing key: {e}")
		return prompt + f" (Formatting error: missing key {e})"

class JoyCaptionOllamaExtraOptions:
    CATEGORY = 'JoyCaption/Ollama'
    FUNCTION = "generate_options"
    RETURN_TYPES = ("JJC_OLLAMA_EXTRA_OPTION",)
    RETURN_NAMES = ("extra_options_ollama",)

    @classmethod
    def INPUT_TYPES(cls):
        return {
            "required": {
                "refer_character_name": ("BOOLEAN", {"default": False}),
                "exclude_people_info": ("BOOLEAN", {"default": False}),
                "include_lighting": ("BOOLEAN", {"default": False}),
                "include_camera_angle": ("BOOLEAN", {"default": False}),
                "include_watermark_info": ("BOOLEAN", {"default": False}),
                "include_JPEG_artifacts": ("BOOLEAN", {"default": False}),
                "include_exif": ("BOOLEAN", {"default": False}),
                "exclude_sexual": ("BOOLEAN", {"default": False}),
                "exclude_image_resolution": ("BOOLEAN", {"default": False}),
                "include_aesthetic_quality": ("BOOLEAN", {"default": False}),
                "include_composition_style": ("BOOLEAN", {"default": False}),
                "exclude_text": ("BOOLEAN", {"default": False}),
                "specify_depth_field": ("BOOLEAN", {"default": False}),
                "specify_lighting_sources": ("BOOLEAN", {"default": False}),
                "do_not_use_ambiguous_language": ("BOOLEAN", {"default": False}),
                "include_nsfw_rating": ("BOOLEAN", {"default": False}),
                "only_describe_most_important_elements": ("BOOLEAN", {"default": False}),
                "do_not_include_artist_name_or_title": ("BOOLEAN", {"default": False}),
                "identify_image_orientation": ("BOOLEAN", {"default": False}),
                "use_vulgar_slang_and_profanity": ("BOOLEAN", {"default": False}),
                "do_not_use_polite_euphemisms": ("BOOLEAN", {"default": False}),
                "include_character_age": ("BOOLEAN", {"default": False}),
                "include_camera_shot_type": ("BOOLEAN", {"default": False}),
                "exclude_mood_feeling": ("BOOLEAN", {"default": False}),
                "include_camera_vantage_height": ("BOOLEAN", {"default": False}),
                "mention_watermark_explicitly": ("BOOLEAN", {"default": False}),
                "avoid_meta_descriptive_phrases": ("BOOLEAN", {"default": False}),
                "character_name": ("STRING", {"default": "", "multiline": False, "placeholder": "e.g., 'Skywalker'"}),
            }
        }

    def generate_options(self, **kwargs):
        option_map = {
            "refer_character_name": "If there is a person/character in the image you must refer to them as {name}.",
            "exclude_people_info": "Do NOT include information about people/characters that cannot be changed (like ethnicity, gender, etc), but do still include changeable attributes (like hair style).",
            "include_lighting": "Include information about lighting.",
            "include_camera_angle": "Include information about camera angle.",
            "include_watermark_info": "Include information about whether there is a watermark or not.",
            "include_JPEG_artifacts": "Include information about whether there are JPEG artifacts or not.",
            "include_exif": "If it is a photo you MUST include information about what camera was likely used and details such as aperture, shutter speed, ISO, etc.",
            "exclude_sexual": "Do NOT include anything sexual; keep it PG.",
            "exclude_image_resolution": "Do NOT mention the image's resolution.",
            "include_aesthetic_quality": "You MUST include information about the subjective aesthetic quality of the image from low to very high.",
            "include_composition_style": "Include information on the image's composition style, such as leading lines, rule of thirds, or symmetry.",
            "exclude_text": "Do NOT mention any text that is in the image.",
            "specify_depth_field": "Specify the depth of field and whether the background is in focus or blurred.",
            "specify_lighting_sources": "If applicable, mention the likely use of artificial or natural lighting sources.",
            "do_not_use_ambiguous_language": "Do NOT use any ambiguous language.",
            "include_nsfw_rating": "Include whether the image is sfw, suggestive, or nsfw.",
            "only_describe_most_important_elements": "ONLY describe the most important elements of the image.",
            "do_not_include_artist_name_or_title": "If it is a work of art, do not include the artist's name or the title of the work.",
            "identify_image_orientation": "Identify the image orientation (portrait, landscape, or square) and aspect ratio if obvious.",
            "use_vulgar_slang_and_profanity": """Use vulgar slang and profanity, such as (but not limited to) "fucking," "slut," "cock," etc.""",
            "do_not_use_polite_euphemisms": "Do NOT use polite euphemisms—lean into blunt, casual phrasing.",
            "include_character_age": "Include information about the ages of any people/characters when applicable.",
            "include_camera_shot_type": "Mention whether the image depicts an extreme close-up, close-up, medium close-up, medium shot, cowboy shot, medium wide shot, wide shot, or extreme wide shot.",
            "exclude_mood_feeling": "Do not mention the mood/feeling/etc of the image.",
            "include_camera_vantage_height": "Explicitly specify the vantage height (eye-level, low-angle worm’s-eye, bird’s-eye, drone, rooftop, etc.).",
            "mention_watermark_explicitly": "If there is a watermark, you must mention it.",
            "avoid_meta_descriptive_phrases": """Your response will be used by a text-to-image model, so avoid useless meta phrases like “This image shows…”, "You are looking at...", etc."""
        }
        selected_options = []
        character_name = kwargs.pop("character_name", "")
        for key, text_template in option_map.items():
            if kwargs.get(key, False):
                selected_options.append(text_template)
        return ((selected_options, character_name),)

class JoyCaptionOllamaPrompter:
    CATEGORY = 'JoyCaption/Ollama'
    FUNCTION = "generate_prompts"
    RETURN_TYPES = ("STRING", "STRING")
    RETURN_NAMES = ("system_prompt", "user_prompt")

    @classmethod
    def INPUT_TYPES(cls):
        req = {
            "caption_type": (list(CAPTION_TYPE_MAP.keys()), {"default": "Descriptive (Casual)"}),
            "caption_length": (CAPTION_LENGTH_CHOICES, {"default": "medium-length"}),
        }
        opt = {
            "extra_options_input": ("JJC_OLLAMA_EXTRA_OPTION",)
        }
        return {"required": req, "optional": opt}

    def generate_prompts(self, caption_type, caption_length, extra_options_input=None):
        extras_list = []
        char_name = ""
        if extra_options_input:
            if isinstance(extra_options_input, tuple) and len(extra_options_input) == 2:
                extras_list, char_name = extra_options_input
                if not isinstance(extras_list, list): extras_list = []
                if not isinstance(char_name, str): char_name = ""
            else:
                print(f"JoyCaption (Ollama Prompter) Warning: extra_options_input is not in the expected format. Received: {type(extra_options_input)}")
        
        user_prompt = build_prompt(caption_type, caption_length, extras_list, char_name)
        
        # Select system prompt based on caption type
        if "tag list" in caption_type.lower():
            if "danbooru" in caption_type.lower():
                system_prompt = """You are a Danbooru tag generator. Generate ONLY comma-separated tags in lowercase with underscores.
                Follow this exact order: artist:, copyright:, character:, meta:, then general tags.
                Include precise counts (1girl, 2boys), specific details about appearance, clothing, accessories, pose, expression, actions, and background.
                Use EXACT Danbooru syntax. NO explanatory text or natural language."""
            elif "e621" in caption_type.lower():
                system_prompt = """You are an e621 tag generator. Generate ONLY comma-separated tags in alphabetical order.
                Follow this exact order: artist:, copyright:, character:, species:, meta:, lore:, then general tags.
                Be extremely precise with tag formatting. NO explanatory text."""
            elif "rule34" in caption_type.lower():
                system_prompt = """You are a Rule34 tag generator. Generate ONLY comma-separated tags in alphabetical order.
                Follow this exact order: artist:, copyright:, character:, meta:, then general tags.
                Be extremely precise and use proper tag syntax. NO explanatory text."""
            else:
                system_prompt = """You are a booru tag generator. Generate ONLY comma-separated descriptive tags.
                Focus on visual elements, character traits, clothing, pose, setting, and actions.
                Use consistent formatting with underscores for multi-word tags. NO explanatory text."""
        elif caption_type == "Stable Diffusion Prompt":
            system_prompt = """You are a Stable Diffusion prompt engineer. Create prompts that work well with Stable Diffusion.
            Focus on visual details, artistic style, camera angles, lighting, and composition.
            Use common SD syntax and keywords. Separate key elements with commas.
            Keep strictly within the specified length limit."""
        elif caption_type == "MidJourney":
            system_prompt = """You are a MidJourney prompt expert. Create prompts optimized for MidJourney.
            Use MidJourney's specific syntax and parameter style.
            Include artistic style, camera view, lighting, and composition.
            Keep strictly within the specified length limit."""
        elif "straightforward" in caption_type.lower():
            system_prompt = """You are a precise image descriptor. Focus on concrete, observable details.
            Begin with main subject and medium. Describe pivotal elements using confident language.
            Focus on color, shape, texture, and spatial relationships.
            Omit speculation and mood. Quote any text exactly. Note technical details like watermarks.
            Keep strictly within word limits. Never use phrases like 'This image shows...'"""
        else:
            system_prompt = """You are an adaptive image description assistant.
            Adjust your style to match the requested caption type exactly.
            Strictly adhere to specified word limits and formatting requirements.
            Be precise, clear, and follow the given style guidelines exactly."""

        # Add length enforcement to system prompt
        if isinstance(caption_length, (int, str)) and str(caption_length).isdigit():
            system_prompt += f"\nIMPORTANT: Your response MUST NOT exceed {caption_length} words."
        elif caption_length in ["very short", "short", "medium-length", "long", "very long"]:
            length_guides = {
                "very short": "25", "short": "50", "medium-length": "100",
                "long": "150", "very long": "200"
            }
            system_prompt += f"\nIMPORTANT: Keep your response approximately {length_guides[caption_length]} words."
            
        return (system_prompt.strip(), user_prompt.strip())

NODE_CLASS_MAPPINGS = {
    "JoyCaptionOllamaPrompter": JoyCaptionOllamaPrompter,
    "JoyCaptionOllamaExtraOptions": JoyCaptionOllamaExtraOptions,
}

NODE_DISPLAY_NAME_MAPPINGS = {
    "JoyCaptionOllamaPrompter": "JoyCaption Ollama Prompter",
    "JoyCaptionOllamaExtraOptions": "JoyCaption Ollama Extra Options",
}
